package com.kg.sdk.util;

import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Helper {
    /**
     * 时间格式
     */
    // private static final String DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss";
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DATE_FORMAT2 = "yyyyMMddHHmmss";
    public static final String DATE_FORMAT1 = "yyyy-MM-dd";
    /**
     * 随机种子
     */
    private static final String RANDOMSEED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    /**
     * 转换字符串为日期类型
     * @param dateStr 日期字符串
     * @return 日期
     */
    public static Date string2Date(String dateStr) {
        return string2Date(dateStr, DATE_FORMAT);
    }
    /**
     * 转换字符串为日期类型
     * @param dateStr 日期字符串
     * @param dateFormat 日期字符串格式
     * @return 日期
     */
    public static Date string2Date(String dateStr, String dateFormat) {
        Date result = null;
        try {
            DateFormat df = new SimpleDateFormat(dateFormat);
            result = df.parse(dateStr);
        } catch (Exception e) {
            result = null;
        }
        return result;
    }
    public static String getUnixDate(){
        long  time = System.currentTimeMillis()/1000L;
        return time+"";
    }
    /**
     * 转换当前日期为字符串
     * @return
     */
    public static String date2String(){
        return date2String(new Date());
    }
    /**
     * 转换当前日期为字符串
     * @param dateFormat
     * @return
     */
    public static String date2String(String dateFormat){
        return date2String(new Date(), dateFormat);
    }
    /**
     * 转换日期为字符串
     * @param date 日期
     * @return 日期字符串
     */
    public static String date2String(Date date){
        return date2String(date, DATE_FORMAT);
    }
    /**
     * 转换日期为字符串
     * @param date 日期
     * @param dateFormat 日期字符串格式
     * @return 日期字符串
     */
    public static String date2String(Date date, String dateFormat){
        String dateStr = "";
        try{
            DateFormat df = new SimpleDateFormat(dateFormat);
            dateStr = df.format(date);
        }catch (Exception e){
            dateStr = "";
        }
        return dateStr;
    }
    /**
     * 日期转换成毫秒
     * @param date
     * @return
     */
    public static long date2Long(Date date){
        return date.getTime();
    }
    /**
     * 当前日期转换成毫秒
     * @return
     */
    public static long date2Long(){
        return new Date().getTime();
    }
    /**
     * 当前日期转换成毫秒字符串
     * @return
     */
    public static String date2LongString(){
        return String.valueOf(date2Long());
    }
    /**
     * 毫秒转换成日期
     * @param ms
     * @return
     */
    public static Date long2Date(long ms){
        return new Date(ms);
    }
    /**
     * 将时间ms数转换为日期字符串
     * @param ms
     * @return
     */
    public static String long2DateString(long ms){
        return long2DateString(ms, DATE_FORMAT);
    }
    /**
     * 将时间ms数转换为日期字符串
     * @param ms
     * @param dateFormat
     * @return
     */
    public static String long2DateString(long ms, String dateFormat){
        String result = null;
        Date date = long2Date(ms);
        if (isNotEmpty(date)){
            result = date2String(date, dateFormat);
        }
        if (isNull(result)){
            result = String.valueOf(ms);
        }
        return result;
    }
    /**
     * 日期字符串转换为ms值
     * @param dateString
     * @return
     */
    public static long dateString2Long(String dateString){
        return dateString2Long(dateString, DATE_FORMAT);
    }
    /**
     * 日期字符串转换为ms值
     * @param dateString
     * @param dateFormat
     * @return
     */
    public static long dateString2Long(String dateString, String dateFormat){
        Date date = string2Date(dateString, dateFormat);
        if (Helper.isNotNull(date)){
            return date2Long(date);
        }
        return 0;
    }

    /**
     * 转换为int
     * @param data 字符串
     * @return
     */
    public static int toInt(String data){
        int result = 0;
        try{
            result = Integer.valueOf(data);
        }catch(Exception ex){
            result = 0;
        }
        return result;
    }
    /**
     * 字符串转换为整数
     * @param data 字符串
     * @param defaultValue 默认值
     * @return
     */
    public static int toInt(String data, int defaultValue){
        int result = Helper.toInt(data);
        if (result == 0){
            result = defaultValue;
        }
        return result;
    }
    /**
     * 转换为long
     * @param data 字符串
     * @return
     */
    public static long toLong(String data){
        long result = 0;
        try{
            result = Long.valueOf(data);
        }catch(Exception ex){
            result = 0;
        }
        return result;
    }
    /**
     * 转换为float
     * @param data 字符串
     * @return
     */
    public static float toFloat(String data){
        float result = 0;
        try{
            result = Float.valueOf(data);
        }catch(Exception ex){
            result = 0;
        }
        return result;
    }
    /**
     * 转换为double
     * @param data 字符串
     * @return
     */
    public static double toDouble(String data){
        double result = 0;
        try{
            result = Double.valueOf(data);
        }catch(Exception ex){
            result = 0;
        }
        return result;
    }
    /**
     * 判断对象是否为NULL或空
     * @param object 对象
     * @return 是否为NULL或空
     */
    public static boolean isEmpty (Object object){
        boolean result = false;
        if (object == null){
            result = true;
        } else {
            if (object instanceof String){
                result = ((String)object).equals("");
            }else if (object instanceof Date) {
                result = ((Date) object).getTime() == 0;
            }else if (object instanceof Long){
                result = ((Long)object).longValue() == Long.MIN_VALUE;
            }else if (object instanceof Integer){
                result = ((Integer)object).intValue() == Integer.MIN_VALUE;
            }else if (object instanceof Collection){
                result = ((Collection<?>)object).size() == 0;
            }else if (object instanceof Map){
                result = ((Map<?, ?>)object).size() == 0;
            }else if (object instanceof JSONObject){
                result = !((JSONObject)object).keys().hasNext();
            }else{
                result = object.toString().equals("");
            }
        }
        return result;
    }
    /**
     * 判断对象是否不为NULL或空
     * @param object 对象
     * @return 是否不为NULL或空
     */
    public static boolean isNotEmpty(Object object){
        return !Helper.isEmpty(object);
    }
    /**
     * 判断对象是否为NULL
     * @param obj 对象
     * @return 是否为NULL
     */
    public static boolean isNull(Object obj){
        return obj == null;
    }
    /**
     * 判断对象是否不为NULL
     * @param obj 对象
     * @return 是否不为NULL
     */
    public static boolean isNotNull(Object obj){
        return !Helper.isNull(obj);
    }
    /**
     * 若判断对象为null输出空值
     * @param obj 输出对象
     * @return
     */
    public static String ifNull(Object obj){
        return Helper.ifNull(obj, "");
    }
    /**
     * 若判断对象为null输出默认值
     * @param obj 输出对象
     * @param defaultValue 默认值
     * @return
     */
    public static String ifNull(Object obj, String defaultValue){
        if (Helper.isNull(obj)){
            return defaultValue;
        }else{
            return obj.toString();
        }
    }

    /**
     * 浮点数转换整数
     * @param f
     * @return
     */
    public static int float2Int(float f){
        return Math.round(f);
    }
    /**
     * 双字节数转换整数
     * @param d
     * @return
     */
    public static int double2Int(double d){
        return Long.valueOf(Math.round(d)).intValue();
    }
    /**
     * 集合转字符串
     * @param obj
     * @return
     */
    public static String set2String(Object obj){
        String result = "";
        if (!Helper.isEmpty(obj)){
            if (obj instanceof Collection){
                Object[] objArray = ((Collection<?>)obj).toArray();
                for(Object tempObj : objArray){
                    if (!Helper.isEmpty(tempObj)){
                        result += "," + tempObj.toString();
                    }
                }
                if (result.length() > 0){
                    result = result.substring(1);
                }
            }else{
                result = obj.toString();
            }
        }
        return result;
    }
    /**
     * 泛型数组转换成列表
     * @param <T>
     * @param array
     * @return
     */
    public static <T extends Object> List<T> array2List(T[] array){
        List<T> result = new ArrayList<T>();
        if (!Helper.isEmpty(array)){
            for(T entity : array){
                result.add(entity);
            }
        }
        return result;
    }

    /**
     * 根据时间生成int类型的tag值
     * @return
     */
    public static int createIntTag(){
        int result = -1;
        try{
            result = Long.valueOf(SystemClock.currentThreadTimeMillis() % Integer.MAX_VALUE).intValue();
        }catch(Exception e){
            result = -1;
        }
        return result;
    }
    /**
     * 取得文件名(从url或本地文件路径)
     * @param path
     * @param ignorExtention 是否忽略后缀
     * @return
     */
    public static String getFileName(String path, boolean ignorExtention){
        String result = path;
        if (Helper.isNotEmpty(path)){
            int startIndex = 0;
            if (result.contains("\\")){
                startIndex = result.lastIndexOf("\\") + 1;
            }else if (result.contains("/")){
                startIndex = result.lastIndexOf("/") + 1;
            }

            int endIndex = ignorExtention ? result.lastIndexOf(".") : result.length();
            result = result.substring(startIndex, endIndex);
        }
        return result;
    }
    /**
     * 取得文件名,无后缀
     * @param file
     * @return
     */
    public static String getFileName(File file){
        String result = "";
        try {
            result = file.getName().substring(0, file.getName().lastIndexOf("."));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 取得文件名,无后缀
     * @param path
     * @return
     */
    public static String getFileName(String path){
        return getFileName(path, true);
    }
    /**
     * 取得文件后缀名
     * @param file
     * @return
     */
    public static String getFileExtension(File file){
        String result = "";
        try {
            result = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 取得文件后缀名
     * @param path
     * @return
     */
    public static String getFileExtension(String path){
        if (Helper.isNotEmpty(path)){
            if (path.contains(".")){
                return path.substring(path.lastIndexOf(".") + 1);
            }else{
                return path;
            }
        }else{
            return "";
        }
    }
    /**
     * 判断两字符串是否相等(区分大小写)
     * @param str1
     * @param str2
     * @param ignorSpace 是否忽略空格
     * @return
     */
    public static boolean equalString(String str1, String str2, boolean ignorSpace){
        return Helper.equalString(str1, str2, ignorSpace, false);
    }
    /**
     * 判断两字符串是否相等(包含对null的判断)
     * @param str1
     * @param str2
     * @param ignorSpace 是否忽略空格
     * @param ignorCase  是否忽略大小写
     * @return
     */
    public static boolean equalString(String str1, String str2, boolean ignorSpace, boolean ignorCase){
        if (Helper.isNull(str1) && Helper.isNull(str2)){
            return true;
        }
        if ((Helper.isNull(str1) && Helper.isNotNull(str2)) || (Helper.isNull(str2) && Helper.isNotNull(str1))){
            return false;
        }
        if (ignorSpace){
            if (ignorCase){
                return str1.trim().toLowerCase().equals(str2.trim().toLowerCase());
            }else{
                return str1.trim().equals(str2.trim());
            }
        }else{
            if (ignorCase){
                return str1.toLowerCase().equals(str2.toLowerCase());
            }else{
                return str1.equals(str2);
            }
        }
    }
    /**
     * 创建随机字符串
     * @param length 随机字符串长度
     * @return
     */
    public static String createRandomString(int length){
        StringBuffer result = new StringBuffer();
        if (length > 0){
            Random random = new Random();
            int seedLength = RANDOMSEED.length();
            for (int i = 0; i < length; i++) {
                result.append(RANDOMSEED.charAt(random.nextInt(seedLength)));
            }
        }
        return result.toString();
    }



    /**
     *
     * function: 验证邮箱(发现如果只有正则，在没有输入@.的情况下，正则很久，类似卡死)
     *
     * @param email
     * @return
     *
     * @ author: aXiBa 2013-12-18 下午3:06:49
     */
    public static boolean checkEmail(String email){

        if(Helper.isEmpty(email)) {
            return false;
        }

        // 先验证@
        int pos = email.indexOf("@");
        if (pos == -1 || pos == 0 || pos == email.length()-1) {
            return false;
        }
        String[] array = email.split("@");
        if (Helper.isNull(array) || array.length != 2) {// 如果邮箱不是xxx@xxx格式
            return false;
        }

        // 验证.在@后面
        int pos_point = array[1].indexOf(".");
        if(pos_point==-1 || pos_point==0 || pos_point==array[1].length()-1) {
            return false;
        }

        String check = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        boolean isMatched = matcher.matches();
        if(isMatched) {
            return true;
        }
        return false;
    }

    /**
     * 验证手机号格式
     * @param mobile
     * @return
     */
    public static boolean checkMobile(String mobile) {
        if(Helper.isEmpty(mobile)) {
            return false;
        }

        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobile))
            return false;
        else
            return mobile.matches(telRegex);
    }

    /**
     * 验证昵称
     * http://www.it165.net/pro/html/201108/410.html
     * @return
     */
    public static boolean checkNickName(String nickname) {
        if(Helper.isEmpty(nickname)) {
            return false;
        }

        /**此正则表达式将上面二者结合起来进行判断，中文、大小写字母和数字**/
        String all  = "^[\\u4e00-\\u9fa5a-zA-Z0-9_]{2,20}$";
        Pattern pattern = Pattern.compile(all);

        return pattern.matcher(nickname).matches();
    }


    /**
     *
     * function: 验证包含中文字符
     *
     * @param email
     * @return
     *
     * @ author: aXiBa 2013-3-15 上午9:46:19
     */
    public static boolean checkChinese(String email){
        String check = "[\u4e00-\u9fa5]";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        boolean isMatched = matcher.find();
        return isMatched;
    }


    // 得到资源id
    public static int getResId(Context context, String pageName, String resName, String type){
        return context.getResources().getIdentifier(resName, type, pageName);
    }
    /**
     * 取得指定名称的图片资源ID
     * @param imageName 图片名称
     * @return
     */
    public static int getImageResMipmapId(Context context, String pageName, String imageName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, imageName, "mipmap");
    }
    /**
     * 取得指定名称的图片资源ID
     * @param imageName 图片名称
     * @return
     */
    public static int getImageResId(Context context, String pageName, String imageName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, imageName, "drawable");
    }
    /**
     * 取得指定名称的图片资源ID
     * @param imageName 图片名称
     * @return
     */
    public static int getImageResId(Context context, String imageName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, context.getPackageName(), imageName, "drawable");
    }
    /**
     * 取得指定名称的图片资源ID
     * @param imageName 图片名称
     * @return
     */
    public static int getColorResId(Context context, String pageName, String imageName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, imageName, "color");
    }
    /**
     *
     * function: 取得指定名称的dimen资源ID
     *
     * @param pageName
     * @param dimenName
     * @return
     *
     * @ author: aXiBa 2013-3-15 上午10:56:42
     */
    public static int getDimenResId(Context context, String pageName, String dimenName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, dimenName, "dimen");
    }
    public static int getDimenResId(Context context, String dimenName){
        //return getGlobalApplicationContext().getResources().getIdentifier(imageName, "drawable", getGlobalApplicationContext().getPackageName());
        return getResId(context, context.getPackageName(), dimenName, "dimen");
    }
    /**
     * 取得指定名称的字符串资源ID
     * @param stringName 字符串名称
     * @return
     */
    public static int getStringResId(Context context, String pageName, String stringName){
        //return getGlobalApplicationContext().getResources().getIdentifier(stringName, "string", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, stringName, "string");
    }
    /**
     * 取得指定名称的字符串资源ID
     * @param stringName 字符串名称
     * @return
     */
    public static int getStringResId(Context context, String stringName){
        //return getGlobalApplicationContext().getResources().getIdentifier(stringName, "string", getGlobalApplicationContext().getPackageName());
        return getResId(context, context.getPackageName(), stringName, "string");
    }
    /**
     * 取得指定style的资源ID
     * @param stringName 字符串名称
     * @return
     */
    public static int getStyleResId(Context context, String pageName, String stringName){
        //return getGlobalApplicationContext().getResources().getIdentifier(stringName, "string", getGlobalApplicationContext().getPackageName());
        return getResId(context, pageName, stringName, "style");
    }

    /**
     * 取得指定style的资源ID
     * @param stringName 字符串名称
     * @return
     */
    public static int getStyleResId(Context context, String stringName){
        //return getGlobalApplicationContext().getResources().getIdentifier(stringName, "string", getGlobalApplicationContext().getPackageName());
        return getResId(context, context.getPackageName(), stringName, "style");
    }
    /**
     * 取得指定名称的布局资源id
     * @param layoutName
     * @return
     */
    public static int getLayoutResId(Context context, String pageName, String layoutName){
        return getResId(context, pageName, layoutName, "layout");
    }
    public static int getLayoutResId(Context context,String layoutName){
        return getResId(context, context.getPackageName(), layoutName, "layout");
    }
    /**
     * 取得指定名称的动画资源id
     * @param animName
     * @return
     */
    public static int getAnimResId(Context context, String pageName, String animName){
        return getResId(context, pageName, animName, "anim");
    }
    /**
     * 取得指定名称的资源id
     * @param idName
     * @return
     */
    public static int getIdResId(Context context, String pageName, String idName){
        return getResId(context, pageName, idName, "id");
    }

    /**
     * 取得指定名称的资源id
     * @param idName
     * @return
     */
    public static int getIdResId(Context context,String idName){
        return getResId(context, context.getPackageName(), idName, "id");
    }
    /**
     * 取得指定名称的资源raw
     * @param idName
     * @return
     */
    public static int getRawResId(Context context, String pageName, String idName){
        return getResId(context, pageName, idName, "raw");
    }
    /**
     * 取得指定名称的样式id
     * @param styleableString
     * @return
     */
    public static int getStyleableResId(Context context, String pageName, String styleableString){
        return getResId(context, pageName, styleableString, "styleable");
    }
    public static int getStyleableResId(Context context, String styleableString){
        //return getResId(context, context.getPackageName(), styleableString, "styleable");
       return context.getResources().getIdentifier(styleableString, "styleable", context.getPackageName());
    }
    public static int getStyleableAttrResId(Context context, String styleableString){
        //return getResId(context, context.getPackageName(), styleableString, "attr");
       return context.getResources().getIdentifier(styleableString, "declare-styleable", context.getPackageName());
    }
    // 显示toast
    public static void showToast(Context context, CharSequence text){
        try{
            Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
            if (Helper.isNotNull(toast)){
                //4.0伤不起啊..
//				toast.cancel();
                toast.setText(text);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.show();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 显示toast
    public static void showToast(Context context, int txtId){
        try{
            Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
            if (Helper.isNotNull(toast)){
                //4.0伤不起啊..
//				toast.cancel();
                toast.setText(context.getText(txtId));
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.show();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 遍历R类得到styleable数组资源下的子资源，1.先找到R类下的styleable子类，2.遍历styleable类获得字段值
     *
     * @param context
     * @param styleableName
     * @param styleableFieldName
     * @return
     */
    public static int getStyleableFieldId(Context context, String styleableName, String styleableFieldName) {
        String className = context.getPackageName() + ".R";
        String type = "styleable";
        String name = styleableName + "_" + styleableFieldName;
        try {
            Class<?> cla = Class.forName(className);
            for (Class<?> childClass : cla.getClasses()) {
                String simpleName = childClass.getSimpleName();
                if (simpleName.equals(type)) {
                    for (Field field : childClass.getFields()) {
                        String fieldName = field.getName();
                        if (fieldName.equals(name)) {
                            return (int) field.get(null);
                        }
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int[] getStyleableIntArray(Context context, String name) {
        try {
            Field[] fields = Class.forName(context.getPackageName() + ".R$styleable").getFields();//.与$ difference,$表示R的子类
            Log.e("fie"," field array name is "+fields+" name is "+name);
            for (Field field : fields) {
                Log.e("fie"," field name is "+field.getName()+" name is "+name);
                if (field.getName().equals(name)) {
                    int ret[] = (int[]) field.get(null);
                    return ret;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 利用反射，获取int数组格式的资源ID，例如styleable
     */
    private static int[] getResourceIDsByName(String resName,String resType,String packageName){
        Class clsR = null;
        int[] ids = null;
        try {
            clsR = Class.forName(packageName + ".R");
            Class[] classes = clsR.getClasses();
            Class desClass = null;
            for(int i=0;i<classes.length;i++){
                String[] temp = classes[i].getName().split("\\$");
                if(temp.length >= 2){
                    if(temp[1].equals(resType)){
                        desClass = classes[i];
                        break;
                    }
                }
            }
            if(desClass != null){
                ids = (int[])desClass.getField(resName).get(resName);
            }
        } catch (Exception e) {
        }
        return ids;
    }

    public static int[] getStyleableArray(Context context,String resName){
        return getResourceIDsByName(resName,"styleable",context.getPackageName());
    }
}
